package com.ledou44.ledourpc.clienthandler;

import com.alibaba.fastjson.JSON;
import com.ledou44.ledourpc.dto.LedouSradDTO;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;

/**
 * @author ledou44
 * 调用服务注册发现中心，寻找Service对应提供者的handler
 */
public class DiscoveryClientHandler extends ChannelHandlerAdapter {
    /**
     * 需要发送给客户端的消息
     */
    private final LedouSradDTO message;

    public DiscoveryClientHandler(LedouSradDTO message) {
        this.message = message;
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        ctx.writeAndFlush(JSON.toJSONString(message));
        super.channelActive(ctx);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        LedouSradDTO ledouSradDTO = JSON.parseObject(String.valueOf(msg), LedouSradDTO.class);
        message.setDiscoveryResult(ledouSradDTO.getDiscoveryResult());
        message.setService(ledouSradDTO.getService());
        ctx.close();
    }
}
